package com.yanchangapp.ui.fragment.purchase;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.yanchangapp.R;
import com.yanchangapp.adapter.PsOrderAdapter;
import com.yanchangapp.model.bean.FilterBean;
import com.yanchangapp.model.bean.PsOrderListBean;
import com.yanchangapp.ui.activity.purchase.PCntOrderEditActivity;
import com.yanchangapp.ui.activity.purchase.PNormalOrderEditActivity;
import com.yanchangapp.ui.activity.purchase.POrderDetailActivity;
import com.yanchangapp.ui.activity.purchase.POrderEnsureActivity;
import com.yanchangapp.ui.activity.purchase.POrderListActivity;
import com.yanchangapp.ui.presenter.PsListFgPresenter;
import com.yanchangapp.ui.view.PsListFgView;
import com.zxl.baselib.ui.base.BaseFragment;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.TipDialog;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * Created by apple on 2019-08-05.
 * description: 订单列表Fragment页面....
 *
 * 出现刷新问题的原因是执行先后的问题
 */
public class PListFragment extends BaseFragment<PsListFgView, PsListFgPresenter> implements PsListFgView {
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.llEmptyMsg)
    LinearLayout llEmptyMsg;
    private String title;
    public static final String TITLE = "title";
    public static final String VALUE = "VALUE";
    private static final String TAG = "tab页";
    private boolean isShow = false;
    private boolean isLoading = false;
    private PsOrderAdapter mPsOrderAdapter;
    private List<PsOrderListBean> mPsOrderListBeans = new ArrayList<>();
    // 请求体需要的各个参数
    private String paramsValue;
    private String keywords = null;
    private int curPage = 1;
    private String startTime = null;
    private String endTime = null;
    private int position = -1;
    private TipDialog mDropDialog;
    @Override
    public void init() {
        if (getArguments() != null) {
            title = getArguments().getString(TITLE);
            // 赋予值....
            paramsValue = getArguments().getString(VALUE);
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_purchase_list;
    }

    @Override
    protected PsListFgPresenter createPresenter() {
        return new PsListFgPresenter((POrderListActivity) getActivity());
    }

    @Override
    public void initView(View rootView) {
        // 初始化Rv
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mPsOrderAdapter = new PsOrderAdapter(R.layout.item_pc_order_list, mPsOrderListBeans);
        mRecyclerView.setAdapter(mPsOrderAdapter);

        if (isShow && !isLoading) {
            loadList();
        }

        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            // 直接刷新列表即可
            refreshList(true);
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore();
            }
        });

        mRxManager.on(POrderListActivity.NOTIFY_FILTER_DATA, new Consumer<FilterBean>() {
            @Override
            public void accept(FilterBean filterBean) throws Exception {
                keywords = filterBean.getKeywords();
                startTime = filterBean.getStartTime();
                endTime = filterBean.getEndTime();
                if (title.equals(filterBean.getTitle())){
                    loadList();
                }
            }
        });

        // 依据订单ID 跳转向Activity
        mPsOrderAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> POrderDetailActivity.show(getActivity(), mPsOrderListBeans.get(i).getOrderId()));

        mPsOrderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                String contractId = mPsOrderListBeans.get(position).getContractId();
                String orderId = mPsOrderListBeans.get(position).getOrderId();
                switch (view.getId()){
                    case R.id.tvDelete:
                        PListFragment.this.position = position;
                        showDropDialog(orderId);
                        break;
                    case R.id.tvModify:
                        if (TextUtils.isEmpty(contractId)){
                            PNormalOrderEditActivity.show(getActivity(),orderId);
                        }else {
                            PCntOrderEditActivity.show(getActivity(),orderId);
                        }
                        break;
                    case  R.id.tvSubmit:
                        POrderEnsureActivity.show(getActivity(),orderId);
                        break;
                        default:
                            break;

                }
            }
        });
    }

    private void showDropDialog(String orderId){
        if (mDropDialog == null){
            mDropDialog = new TipDialog.Builder(getActivity())
                    .setMessage("确定作废订单？")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            mPresenter.dropOrderByID(orderId);
                            tipDialog.dismiss();
                        }
                    }).build();
        }
        mDropDialog.show();
    }


    private void showContent(){
        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }

        if (refreshLayout.getVisibility() == View.GONE){
            refreshLayout.setVisibility(View.VISIBLE);
        }

        if (llEmptyMsg.getVisibility() == View.VISIBLE){
            llEmptyMsg.setVisibility(View.GONE);
        }

    }

    private void showEmpty(){
        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }

        if (refreshLayout.getVisibility() == View.VISIBLE){
            refreshLayout.setVisibility(View.GONE);
        }

        if (llEmptyMsg.getVisibility() == View.GONE){
            llEmptyMsg.setVisibility(View.VISIBLE);
        }
    }

    private void showError(){
        if (llErrorNetwork.getVisibility() == View.GONE){
            llErrorNetwork.setVisibility(View.VISIBLE);
        }

        if (refreshLayout.getVisibility() == View.VISIBLE){
            refreshLayout.setVisibility(View.GONE);
        }

        if (llEmptyMsg.getVisibility() == View.VISIBLE){
            llEmptyMsg.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isShow = isVisibleToUser;
        if (isVisibleToUser) {
            if (!TextUtils.isEmpty(title)) {
                isLoading = true;
                loadList();
            } else {
                isLoading = false;
            }
        }
    }

    private void loadList() {
        // 滑动到了第一个....
        mRecyclerView.scrollToPosition(0);
        refreshList(false);
    }


    /**
     * 刷新数据...
     */
    private void refreshList(boolean isPulling) {
        curPage = 1;
        refreshLayout.resetNoMoreData();
        mPresenter.queryPsList(paramsValue, startTime, endTime, keywords, curPage, isPulling);
    }

    private void loadMore() {
        // 添加数量
        curPage++;
        mPresenter.queryPsList(paramsValue, startTime, endTime, keywords, curPage, false);
    }

    @Override
    public void initListener() {
        btnNextRefresh.setOnClickListener(v -> refreshList(false));
    }

    public void handleRefresh() {
        loadList();
    }


    @Override
    public void queryPsListSuccess(List<PsOrderListBean> psOrderListBeans) {
        // 说明是下拉刷新操作
        Log.e("列表刷新", "queryPsListSuccess: "+title);
        if (curPage == 1) {
            Log.e("列表刷新", "进来了");
            mPsOrderListBeans.clear();
            refreshLayout.finishRefresh();
            if (psOrderListBeans == null || psOrderListBeans.size() == 0) {
                // 空布局
                showEmpty();
            } else {
                // 含有内容
                showContent();
                Log.e("列表刷新", "内容来了");
                mPsOrderListBeans.addAll(psOrderListBeans);
            }
            Log.e(TAG, "为什么这里不刷新呢 = "+Thread.currentThread().getName()+"数量 = "+mPsOrderListBeans.size() );
            mPsOrderAdapter.notifyDataSetChanged();
        } else {
            if (psOrderListBeans == null || psOrderListBeans.size() == 0) {
                // 下拉加载无更多内容
                refreshLayout.finishLoadMoreWithNoMoreData();
                curPage--;
            } else {
                // 含有内容
                mPsOrderListBeans.addAll(psOrderListBeans);
                mPsOrderAdapter.notifyDataSetChanged();
                refreshLayout.finishLoadMore();
            }
        }
    }

    @Override
    public void queryPsListFailure(String err) {
        UIUtils.showToast(err);
        showError();
        if (curPage == 1) {
            refreshLayout.finishRefresh();
        } else {
            curPage--;
            refreshLayout.finishLoadMore();
        }
    }

    @Override
    public void dropOrderFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void dropOrderSuccess() {
        mPsOrderListBeans.remove(position);
        mPsOrderAdapter.notifyItemRemoved(position);
    }
}
